<template>
  <el-card>
    <h4 class="title" border>{{ title }}</h4>
    <el-divider></el-divider>
    <el-form
      :model="testForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <!-- 学       科 -->
      <el-form-item label="学科" prop="subjectID" width="300px">
        <el-select
          @change="getSubjectDirectorys"
          v-model="testForm.subjectID"
          placeholder="请选择"
        >
          <el-option
            v-for="s in simpleSubjectList"
            :key="s.value"
            :label="s.label"
            :value="s.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 目       录 -->
      <el-form-item label="目录" prop="catalogID">
        <el-select v-model.number="testForm.catalogID" placeholder="请选择">
          <el-option
            v-if="!subjectDirectorys.length"
            key="无"
            label="暂无"
            :value="0"
          ></el-option>
          <el-option
            v-else
            v-for="d in subjectDirectorys"
            :key="d.value"
            :label="d.label"
            :value="d.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 企      业 -->
      <el-form-item label="企业" prop="enterpriseID">
        <el-select v-model="testForm.enterpriseID" placeholder="请选择">
          <el-option
            v-for="c in companysList"
            :key="c.id"
            :label="c.company"
            :value="c.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 城     市 -->
      <el-form-item label="城市" prop="city">
        <!--         provinces      -->
        <el-select
          @change="getCitysList"
          class="area"
          v-model="testForm.province"
          placeholder="请选择"
        >
          <el-option
            v-for="p in provinces"
            :key="p"
            :label="p"
            :value="p"
          ></el-option>
        </el-select>
        <!--          citys          -->
        <el-select class="area" v-model="testForm.city" placeholder="请选择">
          <el-option
            v-for="c in citys"
            :key="c"
            :label="c"
            :value="c"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 方     向 -->
      <el-form-item label="方向" prop="direction">
        <el-select v-model="testForm.direction" placeholder="请选择">
          <el-option
            v-for="d in direction"
            :key="d"
            :label="d"
            :value="d"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 题    型 -->
      <el-form-item label="题型" prop="questionType">
        <el-radio-group v-model="testForm.questionType" size="medium">
          <el-radio
            v-for="q in questionType"
            :key="q.value"
            :label="q.value + ''"
            >{{ q.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <!-- 难    度-->
      <el-form-item label="难度" prop="difficulty">
        <el-radio-group v-model="testForm.difficulty" size="medium">
          <el-radio
            v-for="d in difficulty"
            :key="d.value"
            :label="d.value + ''"
            >{{ d.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <!-- 题   干-->
      <el-form-item label="题干" prop="question">
        <QuillEditor
          ref="questionQuill"
          :quillContent="testForm.question"
          type="题干"
        />
      </el-form-item>
      <!-- 选   项 -->
      <el-form-item label="选项" v-if="radioOrBox" prop="options">
        <el-alert
          title="设置完成后，请勾选正确答案"
          type="info"
          style="height: 32px; line-height: 32px"
          :closable="false"
        >
        </el-alert>
        <!-- 需要判断选择的选择题类型，然后显示对应的表单 -->
        <!-- 单选时 -->
        <el-radio-group v-if="radioOrBox === 'single'" v-model="raido">
          <el-radio
            class="eachCheck"
            v-for="i in testForm.options"
            :key="i.code"
            :label="i.code"
          >
            <span class="radioOrCheckBox">{{ i.code }}</span>
            <el-input v-model="i.title" size="small" />
            <div class="img">
              <UploadImg :item="i" @imgHasDone="handleImgUpload" />
            </div>
          </el-radio>
        </el-radio-group>
        <!-- 多选时 -->
        <el-checkbox-group
          v-else-if="radioOrBox === 'repeat'"
          v-model="checkBox"
        >
          <el-checkbox
            class="eachCheck"
            v-for="i in testForm.options"
            :key="i.code"
            :label="i.code"
            name="type"
          >
            <span class="radioOrCheckBox">{{ i.code }}</span>
            <el-input v-model="i.title" size="small" />
            <div class="img">
              <UploadImg :item="i" @imgHasDone="handleImgUpload" />
            </div>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 解析视频 -->
      <el-form-item label="解析视频" prop="videoURL">
        <el-input
          v-model="testForm.videoURL"
          placeholder="请填入地址链接"
        ></el-input>
      </el-form-item>
      <!-- 答案解析 -->
      <el-form-item label="答案解析" prop="answer">
        <QuillEditor
          ref="answerQuill"
          :quillContent="testForm.answer"
          type="答案解析"
        />
      </el-form-item>
      <!-- 题目备注 -->
      <el-form-item label="题目备注" prop="remarks">
        <textarea v-model="testForm.remarks" rows="8" cols="68" style='border:1px solid #dcdfe6'></textarea>
      </el-form-item>
      <!-- 试题标签 -->
      <el-form-item label="试题标签" prop="tags">
        <el-select v-model="testForm.tags" multiple placeholder="请选择">
          <el-option
            v-for="t in simpleTagsList"
            :key="t.value"
            :label="t.label"
            :value="t.label"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :type="btnType" @click="submit">{{ btnContent }}</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import QuillEditor from '@/components/QuillEditor'
import UploadImg from '../components/upload-img.vue'
import { simple } from '@/api/hmmm/subjects.js'
import { simple as simpleDirectory } from '@/api/hmmm/directorys.js'
import { list } from '@/api/hmmm/companys.js'
// 获取试题方向
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as simpleTags } from '@/api/hmmm/tags.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  components: { QuillEditor, UploadImg },
  name: 'QuestionsNew',
  data () {
    return {
      title: '试题录入',
      btnType: 'primary',
      btnContent: '确认添加',
      provinces: [],
      citys: [],
      raido: '',
      checkBox: [],
      testForm: {
        subjectID: '',
        enterpriseID: '',
        catalogID: '', // 目录
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: 0
          }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: [] // ⭐不确定，接口文档要求字符串，但感觉这里应该是数组
      },
      rules: {
        subjectID: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        enterpriseID: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        catalogID: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        province: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        city: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        direction: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        questionType: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        difficulty: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }],
        tags: [{ required: true, message: '此项为必填项', trigger: ['change', 'blur'] }]
      },
      simpleSubjectList: [], // 学科简单列表
      subjectDirectorys: [], // 目录简单列表
      companysList: [],
      direction, // 方向
      difficulty,
      questionType,
      simpleTagsList: []
    }
  },
  computed: {
    // 判断是单选还是多选，还是简答(返回false就是简答)
    radioOrBox () {
      if (this.testForm.questionType === '1') return 'single' // 单选判断
      if (this.testForm.questionType === '2') return 'repeat'
      return false
    }
  },
  created () {
    this.formType()
    this.provinces = provinces()
    this.getSimpleSubjectList()
    this.getCompanysList()
    this.getSimpleTags()
  },
  methods: {
    // 表单类型判断 新增 还是修改(回显)
    async formType () {
      const id = this.$route.query.id
      if (id) { // 此时为修改
        this.title = '试题修改'
        this.btnType = 'success'
        this.btnContent = '确认修改'
        const { data } = await detail({ id })
        // 因为id要求是字符串，所以要拆成数组⭐
        const tags = data.tags.split(',')
        this.testForm = { ...data, tags }
        this.backShowCheck(data)
        console.log('回显', data)
        this.getSubjectDirectorys(data)
      }
    },
    // 修改回显时，显示正确答案
    backShowCheck (data) {
      const arr = []
      data.options.forEach(i => {
        if (i.isRight === 1) arr.push(i.code)
      })
      arr.length === 1 ? this.raido = arr[0] : this.checkBox = arr
    },
    // 提交表单
    submit () {
      this.$refs.ruleForm.validate(async boo => {
        if (!boo) return
        if (!this.formatOptions()) return
        const quillvalue = this.getContent() // 同步一下富文本的内容
        if (!quillvalue) return this.$message.warning('题干和答案不能为空') // ⭐⭐⭐
        this.handleTags()
        console.log(this.testForm)
        if (this.testForm.id) {
          await update(this.testForm)
        } else {
          await add(this.testForm)
        }
        this.testForm.tags = []
        this.$router.push('/questions/list')
      })
    },
    // 选择题提交前调用，格式化选项内容
    formatOptions () {
      const type = this.testForm.questionType
      if (type === '1') { // 如果是单选
        const index = this.testForm.options.findIndex(i => i.code === this.raido)
        // 如果没有选答案，返回
        if (index === -1) {
          this.$message.warning('您还没有选中答案')
          return false
        }
        this.testForm.options.forEach((item, i) => {
          item.isRight = i === index ? 1 : 0
        })
      }
      if (type === '2') {
        console.log(this.checkBox)
        if (this.checkBox.length <= 1) {
          this.$message.warning('您需要选中两个以上的答案')
          return false
        }
        this.testForm.options.forEach(i => {
          i.isRight = this.checkBox.includes(i.code) ? 1 : 0
        })
      }
      return true
    },
    // 获取学科简单列表
    async getSimpleSubjectList () {
      const { data } = await simple()
      this.simpleSubjectList = data
    },
    // 根据选择的学科获取具体学科种类
    async getSubjectDirectorys () {
      const { data } = await simpleDirectory(this.testForm)
      console.log('具体学科种类', data) // a
      this.subjectDirectorys = data
    },
    // 获取企业列表
    async getCompanysList () {
      const { data: { items } } = await list({ page: 1, pagesize: Date.now() })
      this.companysList = items
    },
    // 获取城市地区
    getCitysList () {
      this.testForm.city = ''
      this.citys = citys(this.testForm.province)
    },
    getContent () {
      this.testForm.question = this.$refs.questionQuill.content.trim() // 题干 trim()无效
      this.testForm.answer = this.$refs.answerQuill.content // 答案解析
      if (this.testForm.question && this.testForm.answer) return true
      return false
    },
    // 获取简单标签列表
    async getSimpleTags () {
      const { data } = await simpleTags()
      this.simpleTagsList = data
    },
    // 处理图片上传
    handleImgUpload (hasImgObj) {
      const index = this.testForm.options.findIndex(i => i.code === hasImgObj.code)
      this.testForm.options[index].img = hasImgObj.img
    },
    // 提交表单前，将标签处理成字符串
    handleTags () {
      this.testForm.tags = this.testForm.tags.join(',')
    }
  }
}
</script>

<style scoped lang='scss'>
.title {
  margin: 0;
  padding: 0;
}
.el-form {
  width: 600px;

  .el-form-item {
    width: 100%;
    .el-select {
      width: 100%;
    }
    .area {
      width: 240px;
      &:first-child {
        margin-right: 20px;
      }
    }
  }

  .eachCheck {
    margin: 10px 0;
    .el-input {
      width: 200px;
    }
  }
}
.radioOrCheckBox {
  display: inline-block;
  width: 20px;
}
.img {
  display: inline-block;
  vertical-align: middle;
}
</style>
